// na_1.1.cpp : main project file.

#include <math.h>
#include <stdio.h>

#include "na_1.1.h"

typedef double (*itrFunctor)( const double );

inline void logStep( unsigned int i, double x0, double x1 ) 
{
	printf("iteration step %2d, x%d \t= %1.12f, x%d \t= %1.12f \n", i+1, i, x0, i+1, x1);
}

inline double itrFunction1( const double x0 )
{
    return 10 + x0 - 4 * pow( x0, 2.0 ) - pow( x0, 3.0 );
}

inline double itrFunction2( const double x0 )
{
	return sqrt( ( 10 - x0*x0*x0 ) / 4.0 );
}

inline double itrFunction3( const double x0 )
{
    return sqrt( 10 / ( x0 + 4 ) );
}

inline bool isConverged( const double x0, const double x1)
{
	return fabs( x0 - x1 ) < LIMIT_EPSILON;
}

int na_11()
{
    printf("Start the NA experiment 1.1, basic iteration (1)\n");

	double	x0 = 0.00;
    double	x1 = 0.00;
	int		selected = 0;
    itrFunctor itrFun[3] = { NULL };

    //bind functor
    itrFun[0] = &itrFunction1;
    itrFun[1] = &itrFunction2;
    itrFun[2] = &itrFunction3;

	for ( ; selected != 1 && selected != 2 && selected != 3; )
	{
		printf("Please input which iteration equation you want to test(1~3):");
        scanf_s("%d",&selected);
	}
	--selected;	//to match with the itrFun array

    printf("Please give out the initial value(-100.0 ~ 100.0):");
    scanf_s("%f", &x1);

    printf("Start iteration, equation %d \n", selected);

    unsigned int i = 0;
    for( ; !isConverged( x0, x1 ) && x1<100.0; ++i )
    {
        x0 = x1;
        x1 = itrFun[selected](x0);
        logStep(i, x0, x1);
    }

	if ( !isConverged(x0, x1) )
	{
		printf("Stopped for divergening...\n");
	}
	else
	{
		printf("Converged with %d steps, reaches at x = %1.12f \n", i, x1);
	}

    printf("End of iteration\n");

    return 0;
}
